import { useEffect, useRef, useCallback } from "react";
import * as echarts from "echarts";

interface HorizontalBarProps {
  id: number;
  name: string;
  value: number;
}

export default function HorizontalBar({
  data,
}: {
  data: HorizontalBarProps[];
}) {
  const chartRef = useRef<echarts.ECharts | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  const initEcharts = useCallback(() => {
    const container = containerRef.current;
    if (!container) return;

    if (!chartRef.current) {
      chartRef.current = echarts.init(container);
    }

    const options = {
      xAxis: {
        type: "value",
        show: false,
        max: (value: { max: number }) => {
          return Math.ceil(value.max * 1.2);
        },
      },
      yAxis: {
        type: "category",
        data: data.map((item) => item.name),
        inverse: true,
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { color: "#9EB1C8" },
      },
      grid: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0,
        containLabel: true,
      },
      series: [
        {
          type: "bar",
          data: data.map((item) => ({
            name: item.name,
            value: item.value,
          })),
          showBackground: true,
          backgroundStyle: {
            color: "rgba(180,180,180,0.2)",
          },
          itemStyle: {
            color: "#479AD3",
            borderRadius: 5,
            shadowColor: "rgba(0,0,0,0.3)",
            shadowBlur: 5,
          },
          barWidth: 12,
          label: {
            show: true,
            position: "right",
            color: "#fff",
          },
        },
      ],
    };

    chartRef.current.setOption(options);
  }, [data]);

  useEffect(() => {
    initEcharts();

    const handleResize = () => {
      if (chartRef.current) {
        chartRef.current.resize();
      }
    };

    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
      if (chartRef.current) {
        chartRef.current.dispose();
        chartRef.current = null;
      }
    };
  }, [initEcharts]);

  useEffect(() => {
    if (chartRef.current) {
      chartRef.current.setOption({
        yAxis: {
          data: data.map((item) => item.name),
        },
        series: [
          {
            data: data.map((item) => ({
              name: item.name,
              value: item.value,
            })),
          },
        ],
      });
    }
  }, [data]);

  return (
    <div className="h-1/3 box-border pb-4">
      <div className="text-2xl text-white">【大区数据信息】</div>
      <div ref={containerRef} className="w-full h-full"></div>
    </div>
  );
}
